// pages/Waybill/Waybill.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //运单信息
    waybill: {},
    //跟踪记录
    followData: [],
    //回单记录
    stepData: [
      {
        title: '回单已签收',
        time: '05-14 18:06'
      },
      {
        title: '已寄出',
        time: '05-16 09:37'
      },
      {
        title: '已返回',
        time: '05-19 11:10'
      },
      {
        title: '已返厂',
        time: ''
      },
    ],

    picList: []
  },
  //获取运单详情
  getOrderDetail(id){
    return new Promise(resolve => {
      let url = 'WLAuth/YunDan';
      wx.$get(5,url,{yundanhao: id}).then(res =>{
        resolve();
        if (res.errcode != 0) return;
        let data = res.data.row[0] || {}
        this.setData({waybill: {...data,...this.data.waybill}})
      })
    })
  },
  //获取运单货物汇总
  getGoodsSum(id){
    return new Promise(resolve => {
      let url = `WLAuth/HuoWuHuiZong/${id}`;
      wx.$get(5, url).then(res => {
        resolve();
        if (res.errcode != 0) return;
        let data = res.data.row || [],
          sum = 0;
        data.forEach(item => {
          sum += item.shuliang
        });
        this.setData({
          ['waybill.shuliang']: sum
        })
      })
    })
  },

  //获取跟踪记录
  getFollowRecord(id){
    return new Promise(resolve => {
      let url = `WLAuth/GenZongJiLu?yundanhao=${id}&orderBy=input_time desc`;
      wx.$get(5, url).then(res => {
        resolve();
        if (res.errcode != 0) return;
        let data = res.data.row || [],
          arr = [], //跟踪记录数组
          tab = {}, //物流流程标签
          picList = [];
        data.forEach(item => {
          let {liuchengbiaoqian,jiedian, zhaopian, zhaopian2, zhaopian3, zhaopian4, zhaopian5} = item;

          if (liuchengbiaoqian === '已签收') {
            let arr = [];
            zhaopian && arr.push(zhaopian);
            zhaopian2 && arr.push(zhaopian2);
            zhaopian3 && arr.push(zhaopian3);
            zhaopian4 && arr.push(zhaopian4);
            zhaopian5 && arr.push(zhaopian5);
            arr = arr.join(',').split(',');
            arr = arr.length ? arr.join(',').split(',') : [];
            picList = [...picList, ...arr]
          }

          if (jiedian === '货损'){
            return
          }

          //如果有流程标签
          if (liuchengbiaoqian) {
            if (!tab[liuchengbiaoqian]) {
              arr.push(liuchengbiaoqian)
              tab[liuchengbiaoqian] = [item];
            } else {
              tab[liuchengbiaoqian].push(item);
            }
          } else {
            arr.push(item)
          }
          // tab[item.liuchengbiaoqian] = [...tab[item.liuchengbiaoqian] || [],item]
        });

        let followData = [],
          iconObj = {
            ['仓库处理']: 'icon-cangkukucun',
            ['已发货']: 'icon-yifahuo',
            ['运输中']: 'icon-truck',
            ['已签收']: 'icon-yiqianshou',
          };
        arr.forEach(item => {
          if (typeof item === 'string') {
            tab[item].forEach((ite, index) => {
              if (!index) {
                // followData.push({...ite,isTab: true,icon: iconObj[item]})
                followData.push({
                  isTab: true,
                  icon: iconObj[item],
                  title: ite.liuchengbiaoqian,
                  msg: ite.jiedian,
                  datetime: ite.input_time
                })
              } else {
                // followData.push({...ite,isTab: false})
                followData.push({msg: ite.jiedian, datetime: ite.input_time})
              }
            })
          } else {
            // followData.push({...item,isTab: true})
            followData.push({isTab: true, title: item.jiedian, datetime: item.input_time})
          }
        })
        this.setData({followData, picList})
        console.log(followData);

      })
    })
  },
  //预览照片
  previewPic(){
    let {picList} = this.data;
    if (!picList.length){
      wx.$toast('暂无相关图片');
      return
    }
    wx.previewImage({
      current: picList[0],
      urls: picList
    })
  },
  //微信扫一扫
  wxScanCode(){
    return new Promise(resolve => {
      wx.scanCode({
        success: (res) => {
          if (res.errMsg === "scanCode:ok") {
            console.log("扫码结果");
            console.log(res);
            let {result} = res,
              orderid = result;
            if (result.indexOf('http://yfgpwebapi.fszyrj.com/wlxcx/') >= 0){
              let obj = {};
              for (let i = 1;i<8;i++){
                let item = 'param' + i
                obj[item] = GetUrlString(result,item);
              }
              orderid = obj.param4 || ''
            }

            resolve(orderid);

            this.setData({orderid})
            this.ready(orderid);
          }
        },
        fail: (res) => {
          console.log(res);
          wx.$toast('扫码失败')
        }
      })
    })
  },
  //输入框搜索
  bindSearch(e){
    let {value} = e.detail;
    if (!value) return;
    this.ready(value);
  },
  ready(orderid){
    wx.showLoading({mask: true})
    Promise.all([
      this.getOrderDetail(orderid)
      ,this.getGoodsSum(orderid)
      ,this.getFollowRecord(orderid)
    ]).then(res => {
      wx.hideLoading();
    })

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let {orderid} = options;
    if (!orderid) return;
    this.setData({orderid})
    this.ready(orderid);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
